const sequelize = require("../sequelize_ins");
const { DataTypes } = require("sequelize");
const { read_excel } = require("../../utils");

const core = sequelize.define("department_and_disease", {
  father_id: DataTypes.INTEGER,
  name: DataTypes.STRING,
});

module.exports = {
  core,

  get_initial_data() {
    const path = `${process.cwd()}/assets/department_n_desese.xlsx`;
    const sheets = read_excel(path);
    let res = [];
    for (let { raws } of sheets) {
      res = res.concat(
        raws.map((n) => ({
          id: n["id"],
          name: n["名称"],
          father_id: n["科属"],
        }))
      );
    }
    return res;
  },

  async is_data_initial() {
    return (await this.core.findOne()) !== null;
  },

  async get_department_disease() {
    const data = await this.core.findAll();
    const res = [];
    const father_map = {};
    for (let raw of data) {
      const item = { id: raw.id, name: raw.name };
      if (!raw.father_id) {
        item.oriented = [];
        father_map[item.id] = item.oriented;
        res.push(item);
      } else {
        father_map[raw.father_id].push(item);
      }
    }
    return res;
  },
};
